//
//  BlockGenerator.cpp
//  AvoidTheBlocks
//
//  Created by hoangtx on 6/18/13.
//
//

#include "BlockGenerator.h"
#include "StaticVariables.h"

bool BlockGenerator::init(){
    blockManager = OnStageBlockManager::create();
    blockManager->retain();
    this->schedule(schedule_selector(BlockGenerator::callForADrop), 0.25f);
    
    return true;
}

int BlockGenerator::getRandomIndexExceptThoseThatAreFull(){
    CCArray* columnArrayThatAreFull = blockManager->getColumnArrayThatAreFull();
    int randomIndex;
    bool isValid;
    do {
        randomIndex = rand()%NUMBER_OF_BLOCKS_ON_A_ROW;
        isValid = true;
        for(int i=0;i<columnArrayThatAreFull->count();i++){
            CCInteger* iValue = (CCInteger*)columnArrayThatAreFull->objectAtIndex(i);
            if(randomIndex == iValue->getValue()){
                isValid = false;
                break; //abc
            }
        }
    } while (isValid == false);
    return randomIndex;
}

void BlockGenerator::dropBlock(){
    int dropIndex = getRandomIndexExceptThoseThatAreFull();
    
    Block* block = Block::create();
    block->setBlockToIndex(dropIndex);
    CCCallFuncO* callback = CCCallFuncO::create(blockManager, callfuncO_selector(OnStageBlockManager::checkForScoreARow), block);
    block->fallDown(blockManager->blockArray, callback);

    mainLayer->addChild(block);
    
    
}


void BlockGenerator::callForADrop(cocos2d::CCObject *sender){
    dropBlock();
}